﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Otgruzka.ServicesClients;
using BusinessLogic.Security;
using System.Configuration;
using DataTier.Entities;

namespace Otgruzka.Controls.Product
{
    public partial class ProductList : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
                Bind();
        }


        private void Bind()
        {
            this.Products.DataSource = new ProductsClient().GetNotHiddenProductList(UserPrincipal.Current.UserId);
            this.Products.DataBind();
        }

        protected void Product_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var dataItem = e.Row.DataItem as ProductEntity;
                if (dataItem != null)
                {
                    var HProductID = e.Row.FindControl("HProductID") as HiddenField;
                    if (HProductID != null) HProductID.Value = dataItem.Product.ProductId.ToString(); // e.Row.Cells[0].Text;

                    var HArtikul = e.Row.FindControl("HArtikul") as HiddenField;
                    if (HArtikul != null) HArtikul.Value = dataItem.Product.Artikul; // e.Row.Cells[1].Text;

                    var HProductName = e.Row.FindControl("HProductName") as HiddenField;
                    if (HProductName != null) HProductName.Value = dataItem.Product.ProductName; // e.Row.Cells[2].Text;

                    var HPrice = e.Row.FindControl("HPrice") as HiddenField;
                    if (HPrice != null) HPrice.Value = string.Format("{0:C2}", dataItem.Product.Price); // e.Row.Cells[3].Text;

                    var hlBigImage = e.Row.FindControl("hlBigImage") as HyperLink;
                    if (hlBigImage != null && !string.IsNullOrEmpty(dataItem.Product.ImageBigUrl)) hlBigImage.NavigateUrl = (dataItem.Product.ImageBigUrl[0] != '~') ? string.Format("~{0}", dataItem.Product.ImageBigUrl) : dataItem.Product.ImageBigUrl;

                    var SmallImage = e.Row.FindControl("SmallImage") as Image;
                    if (SmallImage != null && !string.IsNullOrEmpty(dataItem.Product.ImageSmallUrl)) SmallImage.ImageUrl = (dataItem.Product.ImageSmallUrl[0] != '~') ? string.Format("~{0}", dataItem.Product.ImageSmallUrl) : dataItem.Product.ImageSmallUrl;

                }
            }
        }


        protected void btnAddNonExist_Click(object sender, EventArgs e)
        {
            // Сохранение в БД нового товара
            AddNonExistProduct();

            // Перезагрузка Грида с товарами
            Bind();
        }



        /// <summary>
        /// Сохранение нового несуществующего продукта в БД
        /// </summary>
        private void AddNonExistProduct()
        {
            string name = this.ProductName.Text;
            int count = 0;
            try
            {
                count = Convert.ToInt32(this.Productquantity.Text);
            }
            catch (Exception ex)
            { }

            ProductEntity product = new ProductEntity()
            {
                Product = new DataTier.Product()
                {
                    IsUnavailable = true,
                    ProductName = name
                },
                // TODO: Сделать заполнение значения Единицы измерения
                MeasureUnit = new ProductsClient().GetMeasureUnitById(UserPrincipal.Current.UserId, Convert.ToInt32(ConfigurationManager.AppSettings["DefaultMeasureUnitId"]))
            };
            

            int id = new ProductsClient().SaveProduct(UserPrincipal.Current.UserId, product);
        }
    }
}